package Arrays;

/**
 * 作者:hfj
 * 功能:231.2的幂
 * 日期: 2025/10/23 17:44
 */
public class IsPowerOfTwo {
    public static void main(String[] args) {
        int n = 2147483646;
        System.out.println(isPowerOfTwo(n));
    }

    //时间会超时
    public static boolean isPowerOfTwo1(int n) {
        //long startTime  = System.currentTimeMillis();
        if (n == 1 || n== 2){
            return true;
        }

        long temp = 2;
        for (int i = 0; i < n/2; i++) {
            if (temp * 2 == n){
                return true;
            }
            temp *= 2;
        }
        //long endTime   = System.currentTimeMillis();
        //System.out.println(endTime - startTime);
        return false;
    }

    //位与运算:2^x = n 因为n 与 n-1 必然为0 比如8(1000) 7(0111),所以只要判断是否为0即可
    public static boolean isPowerOfTwo(int n) {
        if (n < 1){
            return false;
        }
        return (n & n-1) == 0;
    }
}
